package com.qiku.authority.service.impl;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiku.authority.dao.UserDao;
import com.qiku.authority.pojo.EduConstant;
import com.qiku.authority.pojo.User;
import com.qiku.authority.pojo.UserDTO;
import com.qiku.authority.service.UserService;
import com.qiku.authority.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService{


    @Autowired
    private RedisTemplate<Object , Object> redisTemplate;

    @Autowired
    private UserDao userDao;


    @Override
    public UserDTO<User> login(String phone, String password) {
        // 准备返回值对象
        UserDTO dto = new UserDTO();

        // 创建条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone" , phone);
        Integer count = userDao.selectCount(queryWrapper);
        if (count <= 0){ // 手机号不存在
           dto.setState(EduConstant.ERROR_NOT_FOUND_PHONE_CODE);
           dto.setMessage(EduConstant.ERROR_NOT_FOUND_PHONE);
           dto.setContent(null);
        }else {
            // 继续验证密码
            queryWrapper.eq("password" , password);
            User user = userDao.selectOne(queryWrapper);
            if (user == null){ // 密码不正确
                dto.setState(EduConstant.ERROR_PASSWORD_CODE);
                dto.setMessage(EduConstant.ERROR_PASSWORD);
                dto.setContent(null);
            }else {// 登录成功
                dto.setState(EduConstant.LOGIN_SUCCESS_CODE);
                dto.setMessage(EduConstant.LOGIN_SUCCESS);
                String token = JwtUtils.createToken(user); // 生成令牌
                dto.setContent(user);
                dto.setToken(token);
                // 将令牌保存在redis
                redisTemplate.opsForValue().set(token , token , 15 * 60, TimeUnit.SECONDS);
                System.out.println("token: " + token);
            }
        }
        return dto;
    }


    @Override
    public UserDTO<User> check(String token) {
        UserDTO dto = new UserDTO();

        int verify = JwtUtils.isVerify(token);
        switch (verify){
            case EduConstant.TOKEN_SUCCESS_CODE:
                dto.setState(EduConstant.TOKEN_SUCCESS_CODE);
                dto.setMessage(EduConstant.TOKEN_SUCCESS);
                // 重新设置过期时间
                // 重新生成token令牌 需要user
                int userId = JwtUtils.parseTokenUserId(token); // 从token中解析userId
                User user = userDao.selectById(userId); // 获取user
                String newToken = JwtUtils.createToken(user);
                dto.setToken(newToken);
                redisTemplate.delete(token);  // 删除原来的 token
                redisTemplate.opsForValue().set(newToken , newToken , 15 * 60 , TimeUnit.SECONDS);
                break;
            case EduConstant.TOKEN_TIMEOUT_CDOE:
                dto.setState(EduConstant.TOKEN_TIMEOUT_CDOE);
                dto.setMessage(EduConstant.TOKEN_TIMEOUT);
                break;
            case EduConstant.TOKEN_NULL_CODE:
                dto.setState(EduConstant.TOKEN_NULL_CODE);
                dto.setMessage(EduConstant.TOKEN_ERROR1);
                break;
            case EduConstant.TOKEN_ERROR_CDOE:
                dto.setState(EduConstant.TOKEN_ERROR_CDOE);
                dto.setMessage(EduConstant.TOKEN_ERROR2);
                break;
        }
        return dto;
    }



    @Override
    public UserDTO loginPhoneSms(String phoneNumber) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone" , phoneNumber);
        User user = userDao.selectOne(queryWrapper);
        if (user == null){ // 证明手机号尚未注册
            // 注册
            register(phoneNumber , phoneNumber , "手机用户XXXX" , "xxxx");
            return loginPhoneSms(phoneNumber);
        }
        System.out.println("user : " + user);
        // 创建令牌
        String token = JwtUtils.createToken(user);
        UserDTO<User> dto = new UserDTO<>();
        dto.setToken(token);
        dto.setState(EduConstant.LOGIN_SUCCESS_CODE);
        dto.setMessage(EduConstant.LOGIN_SUCCESS);
        dto.setContent(user);
        // 将令牌存入redis
        redisTemplate.opsForValue().set(token , token , 15 * 60 , TimeUnit.SECONDS);

        return dto;
    }


    public Integer register(String phoneNumber, String password, String nickname, String headimg) {
        User user = new User();
        user.setPhone(phoneNumber);
        user.setPassword(password);
        user.setName(nickname);
        user.setPortrait(headimg);
        return userDao.insert(user);
    }

}
